package tt.dz.egobus.servicemanager.core.filter;

import com.thetransactioncompany.cors.CORSFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import java.io.IOException;

/**
 * @author Anson
 * @date 17-4-13
 * @name 跨域处理
 * 当前服务是否处理，观察当前项目中是否存在cors.filter文件
 * 若存在当前文件，则说明需要进行 跨域处理，反之不需要
 * @since 1.0.4
 */
@WebFilter(urlPatterns = "/*", filterName = "egobusCors", initParams = {
        @WebInitParam(
                name = "cors.allowOrigin", value = "*"
        ),
        @WebInitParam(
                name = "cors.supportedMethods", value = "GET, POST, HEAD, PUT, DELETE"
        ),
        @WebInitParam(
                name = "cors.supportedHeaders", value = "Accept, Origin, X-Requested-With, Content-Type, Last-Modified"
        ),
        @WebInitParam(
                name = "cors.exposedHeaders", value = "Set-Cookie"
        ),
        @WebInitParam(
                name = "cors.supportsCredentials", value = "true"
        )
})
public class CrossDomainFilter extends CORSFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(CrossDomainFilter.class);

    private final CorsEnable corsEnable;

    private boolean isCors;

    public CrossDomainFilter() {
        this.corsEnable = new FileExistCorsEnable();
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.info("跨域处理filter初始化......");
        isCors = (corsEnable != null && corsEnable.isEnable());
        LOGGER.info("跨域处理filter是否需要跨域处理isCors={}", isCors);
        if (isCors) {
            super.init(filterConfig);
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (isCors) {
            super.doFilter(request, response, chain);
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {
        LOGGER.info("跨域处理filter销毁......");
        if (isCors) {
            super.destroy();
        }
    }
}
